package com.zhangzhenwei.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhangzhenwei.demo.Util.CopyUtil;
import com.zhangzhenwei.demo.Util.SnowFlake;
import com.zhangzhenwei.demo.domain.Doc;
import com.zhangzhenwei.demo.domain.DocExample;
import com.zhangzhenwei.demo.mapper.DocMapper;
import com.zhangzhenwei.demo.req.DocQueryReq;
import com.zhangzhenwei.demo.req.DocSaveReq;
import com.zhangzhenwei.demo.resp.DocQueryResp;
import com.zhangzhenwei.demo.resp.PageResp;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;
import java.util.List;

@Service
public class DocService {
    @Resource
    private DocMapper DocMapper;
    @Resource
    private SnowFlake snowFlake;
    public PageResp<DocQueryResp> list(DocQueryReq req){
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Doc> docList = DocMapper.selectByExample(docExample);
        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        List<DocQueryResp> list= CopyUtil.copyList(docList, DocQueryResp.class);
        PageResp<DocQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public List<DocQueryResp> all(){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        List<Doc> docList = DocMapper.selectByExample(docExample);
        List<DocQueryResp> list = CopyUtil.copyList(docList,DocQueryResp.class);
        return list;
    }
    public void save(DocSaveReq req){
        Doc doc = CopyUtil.copy(req,Doc.class);
        if (ObjectUtils.isEmpty(req.getId())){
            doc.setId(snowFlake.nextId());
            DocMapper.insert(doc);
        }else {
            DocMapper.updateByPrimaryKey(doc);
        }
    }
    public void delete(Long id){
        DocMapper.deleteByPrimaryKey(id);

    }
}

